package com.example.xunua_mymusic.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xunua_mymusic.LoginActivity;
import com.example.xunua_mymusic.MainActivity;
import com.example.xunua_mymusic.R;
import com.example.xunua_mymusic.entitys.Music;
import com.example.xunua_mymusic.utils.FragmentUtils;
import com.example.xunua_mymusic.view.RoundImageView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class mainFragment extends Fragment implements View.OnClickListener{
    ImageView left_img;
    ViewPager viewPager;
    List<View> vplist=new ArrayList<>();
    RadioButton rb1,rb2,rb3;
    EditText et_add;
    TextView tv_add;
    int []btns={R.id.main_fragment_rb01,R.id.main_fragment_rb02,R.id.main_fragment_rb03};
    Boolean isnew=true;
    ArrayList<HashMap<String,Object>> array_menu;
    MySongAdapter adaptermenu;
    SharedPreferences sharedPreferences;



    public mainFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_main, container, false);
        sharedPreferences=getActivity().getSharedPreferences("MusicList",Context.MODE_PRIVATE);
        view.findViewById(R.id.main_fragment_rb01).performClick();
        viewPager=view.findViewById(R.id.main_fragment_viewpager);
        left_img=view.findViewById(R.id.left_menu);
        final DrawerLayout drawerLayout=getActivity().findViewById(R.id.chouti);
        left_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        rb1=view.findViewById(R.id.main_fragment_rb01);
        rb2=view.findViewById(R.id.main_fragment_rb02);
        rb3=view.findViewById(R.id.main_fragment_rb03);
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        rb3.setOnClickListener(this);
        LayoutInflater layoutInflater=LayoutInflater.from(getContext());
        View view1 = layoutInflater.inflate(R.layout.viewpager_main_first,null);
        View view2 =layoutInflater.inflate(R.layout.viewpager_main_second,null);
        View view3 = layoutInflater.inflate(R.layout.viewpager_main_third, null);
        vp1(view1);
        vp2(view2);
        vp3(view3);
        vplist.add(view1);
        vplist.add(view2);
        vplist.add(view3);
        viewPager.setAdapter(new MyAdapter());
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Button btn=view.findViewById(btns[position]);
                btn.performClick();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_fragment_rb01:
                viewPager.setCurrentItem(0);
                break;
            case R.id.main_fragment_rb02:
                viewPager.setCurrentItem(1);
                break;
            case R.id.main_fragment_rb03:
                viewPager.setCurrentItem(2);
                break;
        }
    }

    private class MyAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return vplist.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view==object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(vplist.get(position));
            return vplist.get(position);
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//            super.destroyItem(container, position, object);
            container.removeView(vplist.get(position));
        }
    }
    void vp1(View view){
        TextView tv_name1=view.findViewById(R.id.main_fragment_tvname);
        RoundImageView imageView=view.findViewById(R.id.vp_first_img_icon);
        MainActivity mainActivity= (MainActivity) getActivity();
        String username=mainActivity.getUserName();
        if (username!=null){
            tv_name1.setText(username);
            Drawable drawable = getResources().getDrawable(R.mipmap.douzi);
            imageView.setBackground(drawable);
        }
        LinearLayout line=view.findViewById(R.id.main_login_register);
        line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });
        GridView gridView=view.findViewById(R.id.vp_first_gridview);
        ListView listView01=view.findViewById(R.id.vp_first_lv01);
        final ListView listView02=view.findViewById(R.id.vp_first_lv02);
        String[] name={"本地音乐","歌曲下载","MV下载","最近播放"};
//        MainActivity mainActivity= (MainActivity) getActivity();
        ArrayList<Music> musicList = mainActivity.getMusic();
        final String[] number={musicList.size()+"首","没有下载任务","没有下载任务","0首"};
        int[] image={R.mipmap.img_main_localmusic,R.mipmap.img_main_musicload,R.mipmap.img_main_mvload,R.mipmap.img_main_playrecently};
        int[] bg_color={R.color.deepgreen,R.color.lightgreen,R.color.lightgreen,R.color.midgreen};
        int[] bg_image={R.mipmap.my_fragment_local_music_decorate,R.color.alpha,R.color.alpha,R.mipmap.my_fragment_recent_play_decorate};
        ArrayList<HashMap<String,Object>> arrayList=new ArrayList<>();
        for (int i = 0; i < image.length; i++) {
            HashMap<String,Object> hs=new HashMap<>();
            hs.put("image",image[i]);
            hs.put("name",name[i]);
            hs.put("number",number[i]);
            hs.put("bg_color",bg_color[i]);
            hs.put("bg_image",bg_image[i]);
            arrayList.add(hs);
        }
        String[] eggs = {"image","name","number","bg_color","bg_image"};
        int[] bag = {R.id.img_main_gv,R.id.txt_main_gv_name,R.id.txt_main_gv_number,R.id.img_main_gv_background_color,R.id.img_main_gv_background_image};
        SimpleAdapter adapter=new SimpleAdapter(getActivity(),arrayList,R.layout.gridview_main,eggs,bag);

        gridView.setAdapter(adapter);
        setlv01(listView01);
        setlv02(listView02);
        final TextView tv_main_add=view.findViewById(R.id.txt_main_newMenu);
        listView02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isnew) {
                    builder(listView02);
                }
            }
        });
        tv_main_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder(listView02);
            }
        });

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        //本地音乐
                        FragmentUtils fragmentUtils=new FragmentUtils();
                        fragmentUtils.show(getFragmentManager(),1);
                        break;
                }
            }
        });
    }
    private void builder(final ListView listView02){

        AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
        builder.setTitle("新建歌单");
        View view1 = LayoutInflater.from(getContext()).inflate(R.layout.viewpager_first_lv_add, null);
        builder.setView(view1);
        et_add=view1.findViewById(R.id.vp_first_lv_add);
        tv_add=view1.findViewById(R.id.vp_first_lv_tv);
        et_add.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_add.setText("("+et_add.getText().length()+"/20)");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isnew) {
                    array_menu.remove(0);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putBoolean("isnew",false);
                    edit.commit();
                    isnew=false;
                }
                String name=et_add.getText().toString().trim();
                HashMap<String,Object> hs=new HashMap<>();
                hs.put("image", R.mipmap.img_main_collectsonglist);
                hs.put("name", name);
                hs.put("number", 0);
                array_menu.add(hs);

                List<String> list=new ArrayList<>();
                for (int i = 0; i < array_menu.size(); i++) {
                    list.add(array_menu.get(i).get("name").toString());
                }
                SharedPreferences.Editor edit = sharedPreferences.edit();
                Gson gson=new Gson();
                edit.remove("names");
                edit.putString("names",gson.toJson(list));
                edit.commit();
                adaptermenu.notifyDataSetChanged();
                //刷新lv高度
                setListViewHeightBasedOnChildren(listView02);
            }
        }).show();
    }
    void vp2(View view){
        ImageView img=view.findViewById(R.id.viewpager_item_second_img);
        AnimationDrawable animationDrawable= (AnimationDrawable) img.getBackground();
        animationDrawable.start();

    }
    void vp3(View view){
        WebView wb=view.findViewById(R.id.webview);
        wb.setWebViewClient(new WebViewClient());
        wb.loadUrl("https://i.y.qq.com/n2/m/share/details/toplist.html?ADTAG=myqq&from=myqq&channel=10007100&id=4");
        WebSettings wbSettings = wb.getSettings();
        wbSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        wbSettings.setJavaScriptEnabled(true);
        wbSettings.setSupportMultipleWindows(true);
        wbSettings.setBuiltInZoomControls(true);
        wb.setWebViewClient(new WebViewClient());
        wb.setClickable(true);
        wb.setWebChromeClient(new WebChromeClient());
        wb.setFocusable(false);
    }

    //我的收藏
    private void setlv01(ListView listView){
        String []name={"我的最爱","收藏的歌单"};
        String []number={"0首","0个"};
        int[] image = {R.mipmap.img_main_mycollect,R.mipmap.img_main_collectsonglist};
        ArrayList<HashMap<String, Object>> array = new ArrayList<>();
        for (int i = 0; i < image.length; i++) {
            HashMap<String, Object> hs = new HashMap<>();
            hs.put("image", image[i]);
            hs.put("name", name[i]);
            hs.put("number", number[i]);
            array.add(hs);
        }
        MySongAdapter adapter=new MySongAdapter(array,getContext());
        listView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(listView);
    }
    //新建歌单
    private void setlv02(ListView listView){
        String[] name={"点击新建歌单"};
        String[] number={""};
        int[] image={R.mipmap.img_main_newoneclick};
        array_menu = new ArrayList<>();
        isnew=sharedPreferences.getBoolean("isnew",true);
        if (isnew) {
            for (int i = 0; i < name.length; i++) {
                HashMap<String, Object> hs = new HashMap<>();
                hs.put("image", image[i]);
                hs.put("name", name[i]);
                hs.put("number", number[i]);
                array_menu.add(hs);
            }
        }else {
            List<String> namelist;
            String names = sharedPreferences.getString("names", null);
            if (names != null){
                Gson gson=new Gson();
                namelist=gson.fromJson(names,new TypeToken<List<String>>(){}.getType());
                for (int i = 0; i < namelist.size(); i++) {
                    HashMap<String, Object> hs = new HashMap<>();
                    hs.put("image", R.mipmap.img_main_collectsonglist);
                    hs.put("name", namelist.get(i));
                    hs.put("number", number[0]);
                    array_menu.add(hs);
                }
            }
        }
        adaptermenu =new MySongAdapter(array_menu,getContext());
        listView.setAdapter(adaptermenu);
        setListViewHeightBasedOnChildren(listView);
    }

    /**
     *避免listview在scroll布局中只显示第一条item
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    private class MySongAdapter extends BaseAdapter{
        ArrayList<HashMap<String, Object>> mDatas;
        Context context;

        public MySongAdapter(ArrayList<HashMap<String, Object>> mDatas, Context context) {
            this.mDatas = mDatas;
            this.context = context;
        }

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return mDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if (convertView == null) {
                viewHolder=new ViewHolder();
                convertView=LayoutInflater.from(getActivity()).inflate(R.layout.listview_vp_first,null);
                viewHolder.img=convertView.findViewById(R.id.img_main_lv);
                viewHolder.tv_name=convertView.findViewById(R.id.txt_main_lv_name);
                viewHolder.tv_number=convertView.findViewById(R.id.txt_main_lv_number);
                convertView.setTag(viewHolder);
            }else {
                viewHolder= (ViewHolder) convertView.getTag();
            }
            viewHolder.img.setImageResource((Integer) mDatas.get(position).get("image"));
            viewHolder.tv_name.setText(mDatas.get(position).get("name")+"");
            viewHolder.tv_number.setText(mDatas.get(position).get("number")+"");
            return convertView;
        }
        private class ViewHolder{
            ImageView img;
            TextView tv_name,tv_number;
        }
    }
}

